<template>
  <!-- 坞修单 在线报价 -->
  <div class="DockOrderOnlineQuotation" v-if="info">
    <!-- 验证密码 -->
    <div v-if="isCheckPassword" class="g-con">
      <div class="checkPassword flexcc-col">
        <div class="">{{ t('DockOrderOnlineQuotation.t1') }}</div>
        <el-form ref="checkPasswordFormEl" :model="checkPasswordFormData" :rules="checkPasswordRules" status-icon label-position="left" class="wp-100" @submit.prevent="handleCheckPassword">
          <el-form-item label="" prop="accessPassword">
            <el-input type="password" v-model.trim="checkPasswordFormData.accessPassword" class="mt-2"></el-input>
          </el-form-item>
        </el-form>
        <el-button type="primary" class="mt-4" @click="handleCheckPassword">
          {{ t('confirmText') }}
        </el-button>
      </div>
    </div>

    <!-- 密码验证通过 -->
    <div v-if="isValidPassword" class="g-con">
      <el-form ref="formEl" :model="formData" :rules="rules" label-width="120px" label-position="left" label-suffix="：">
        <div class="info grid-2">
          <div class="flexsc nowrap">
            <div>{{ t('DockOrderOnlineQuotation.t2') }}：</div>
            <el-input v-if="type === 'add'" v-model.trim="formData.quotationNo" :placeholder="t('DockOrderOnlineQuotation.t3')" style="width: 400px"></el-input>
            <div v-if="type === 'detail'">
              <b>{{ formData.quotationNo }}</b>
            </div>
          </div>
          <div class="flexec" style="padding-right: 80px">
            {{ t('DockOrderOnlineQuotation.t4') }}：<b>{{ dateFormat(info.dockShowInfoVo.quotationEndTime) }}</b>
          </div>
        </div>

        <div class="info ship mt-2" v-if="info.shcwShippingVo">
          <!-- <div class="left">
            <img
              :src="info.shcwShippingVo.picture"
              alt=""
            />
          </div> -->
          <div class="right">
            <div class="title flexsc">
              <div class="a mr-2">{{ info.shcwShippingVo.shippingName }}</div>
              <div class="b flexcc">{{ t(`dockRepair.IMOnumber`) }}:{{ info.shcwShippingVo.shippingNo }}</div>
            </div>
            <div class="attr mt-2">
              <div class="item">
                <span>{{ t(`dockRepair.attr1`) }}:</span>
                <span>{{ getDictLabel('ships_type', info.shcwShippingVo.shippingType) }}</span>
              </div>
              <div class="item">
                <span>{{ t(`dockRepair.attr2`) }}:</span>
                <span>{{ info.shcwShippingVo.totalLength }}</span>
              </div>
              <div class="item">
                <span>{{ t(`dockRepair.attr3`) }}:</span>
                <span>{{ info.shcwShippingVo.yearOfConstruction }}</span>
              </div>
              <div class="item">
                <span>{{ t(`dockRepair.attr4`) }}:</span>
                <span>{{ info.shcwShippingVo.nationality }}</span>
              </div>
              <div class="item">
                <span>{{ t(`dockRepair.attr5`) }}:</span>
                <span>{{ getDictLabel('classification_society', info.shcwShippingVo.classificationSociety) }}</span>
              </div>
              <div class="item">
                <span>{{ t(`dockRepair.attr6`) }}:</span>
                <span>{{ info.shcwShippingVo.portRegistry }}</span>
              </div>
              <div class="item">
                <span>{{ t(`dockRepair.attr7`) }}:</span>
                <span>{{ info.shcwShippingVo.shipowner }}</span>
              </div>
              <div class="item">
                <span>{{ t(`dockRepair.attr8`) }}:</span>
                <span>{{ info.shcwShippingVo.shipManagement }}</span>
              </div>
            </div>
          </div>
        </div>

        <div class="info mt-3 keyword">
          <div class="tit">
            {{ t('DockOrderOnlineQuotation.t35') }}
          </div>
          <div class="con flexsb mt-2">
            <div class="item" v-for="item in info.dockShowInfoVo.dockImportProjectBoList" :key="item.projectId">
              {{ item.projectName }}
            </div>
          </div>
        </div>

        <div class="info sm mt-3">
          <div class="tit">
            {{ t('DockOrderOnlineQuotation.t9') }}
          </div>
          <div class="con mt-2" v-if="type === 'add'">
            <el-form-item :label="t('DockOrderOnlineQuotation.sm_l1')" prop="statementRepairPeriod">
              <div class="lx-flex-start">
                <span class="lx-flex-shrink-0">{{ t('DockOrderOnlineQuotation.default.s1-1') }}</span>
                <el-input type="number" v-model="illustrate.statementRepairPeriod[0].value" :min="0" class="illustrate-input lx-flex-shrink-0" />
                <span class="lx-flex-shrink-0">{{ t('DockOrderOnlineQuotation.default.s1-2') }}</span>
                <el-input type="number" v-model="illustrate.statementRepairPeriod[1].value" :min="0" class="illustrate-input lx-flex-shrink-0" />
                <span class="lx-flex-shrink-0">{{ t('DockOrderOnlineQuotation.default.s1-3') }}</span>
                <el-input type="number" v-model="illustrate.statementRepairPeriod[2].value" oninput="if(value){value=value.replace(/[^\d]/g,'')} if(value<=0){value=0} if(value>100){value=100}" class="illustrate-input lx-flex-shrink-0" />
                <span class="lx-flex-shrink-0">{{ t('DockOrderOnlineQuotation.default.s1-4') }}</span>
              </div>
            </el-form-item>

            <el-form-item :label="t('DockOrderOnlineQuotation.sm_l2')" prop="statementPrice">
              {{ t('DockOrderOnlineQuotation.default.s2') }}
            </el-form-item>

            <el-form-item :label="t('DockOrderOnlineQuotation.sm_l3')" prop="statementPayment">
              <div class="lx-flex-start">
                <el-input type="number" v-model="illustrate.statementPayment[0].value" oninput="if(value){value=value.replace(/[^\d]/g,'')} if(value<=0){value=0} if(value>100){value=100}" class="illustrate-input lx-flex-shrink-0" />
                <span class="lx-flex-shrink-0">{{ t('DockOrderOnlineQuotation.default.s3-1') }}</span>
                <el-input type="number" v-model="illustrate.statementPayment[1].value" oninput="if(value){value=value.replace(/[^\d]/g,'')} if(value<=0){value=0} if(value>100){value=100}" class="illustrate-input lx-flex-shrink-0" />
                <span class="lx-flex-shrink-0">{{ t('DockOrderOnlineQuotation.default.s3-2') }}</span>
                <el-input type="number" v-model="illustrate.statementPayment[2].value" :min="0" class="illustrate-input lx-flex-shrink-0" />
                <span class="lx-flex-shrink-0">{{ t('DockOrderOnlineQuotation.default.s3-3') }}</span>
              </div>
            </el-form-item>

            <el-form-item :label="t('DockOrderOnlineQuotation.sm_l4')" prop="statementDelayPenalty">
              <div class="lx-flex-start">
                <span class="lx-flex-shrink-0">{{ t('DockOrderOnlineQuotation.default.s4-1') }}</span>
                <el-input type="number" v-model="illustrate.statementDelayPenalty[0].value" :min="0" class="illustrate-input lx-flex-shrink-0" />
                <span class="lx-flex-shrink-0">{{ t('DockOrderOnlineQuotation.default.s4-2') }}</span>
                <el-input type="number" v-model="illustrate.statementDelayPenalty[1].value" oninput="if(value){value=value.replace(/[^\d]/g,'')} if(value<=0){value=0} if(value>100){value=100}" class="illustrate-input lx-flex-shrink-0" />
                <span class="lx-flex-shrink-0">{{ t('DockOrderOnlineQuotation.default.s4-3') }}</span>
              </div>
            </el-form-item>

            <el-form-item :label="t('DockOrderOnlineQuotation.sm_l5')" prop="statementValidity">
              <div class="lx-flex-start">
                <span class="lx-flex-shrink-0">{{ t('DockOrderOnlineQuotation.default.s5-1') }}</span>
                <el-input type="number" v-model="illustrate.statementValidity[0].value" :min="0" class="illustrate-input lx-flex-shrink-0" />
                <span class="lx-flex-shrink-0">{{ t('DockOrderOnlineQuotation.default.s5-2') }}</span>
              </div>
            </el-form-item>

<!--            <el-form-item
              :label="t('DockOrderOnlineQuotation.t17')"
              prop="rate"
              v-if="info.dockShowInfoVo.quoteOrderCurrency === 'currency_1'"
            >
              <el-input-number
                v-model.trim="formData.rate"
                :controls="false"
                :min="0"
                :max="100"
                placeholder="%"
                style="width: 100%"
              />
            </el-form-item>-->

            <el-form-item :label="t('DockOrderOnlineQuotation.t48')" prop="quoteDescription">
              <el-input type="textarea" v-model="formData.quoteDescription" autosize />
            </el-form-item>
          </div>
          <div class="con mt-2" v-if="type === 'detail'">
            <div class="item">
              <div class="label">{{ t('DockOrderOnlineQuotation.sm_l1') }}:</div>
              <div class="value">
                <div class="lx-flex-start">
                  <span class="lx-flex-shrink-0">{{ t('DockOrderOnlineQuotation.default.s1-1') }}</span>
                  <span class="lx-flex-shrink-0">{{ illustrate.statementRepairPeriod[0].value }}</span>
                  <span class="lx-flex-shrink-0">{{ t('DockOrderOnlineQuotation.default.s1-2') }}</span>
                  <span class="lx-flex-shrink-0">{{ illustrate.statementRepairPeriod[1].value }}</span>
                  <span class="lx-flex-shrink-0">{{ t('DockOrderOnlineQuotation.default.s1-3') }}</span>
                  <span class="lx-flex-shrink-0">{{ illustrate.statementRepairPeriod[2].value }}</span>
                  <span class="lx-flex-shrink-0">{{ t('DockOrderOnlineQuotation.default.s1-4') }}</span>
                </div>
              </div>
            </div>
            <div class="item mt-2">
              <div class="label">{{ t('DockOrderOnlineQuotation.sm_l2') }}:</div>
              <div class="value">
                {{ t('DockOrderOnlineQuotation.default.s2') }}
              </div>
            </div>
            <div class="item mt-2">
              <div class="label">{{ t('DockOrderOnlineQuotation.sm_l3') }}:</div>
              <div class="value" style="white-space: pre-wrap">
                <div class="lx-flex-start">
                  <span class="lx-flex-shrink-0">{{ illustrate.statementPayment[0].value }}</span>
                  <span class="lx-flex-shrink-0">{{ t('DockOrderOnlineQuotation.default.s3-1') }}</span>
                  <span class="lx-flex-shrink-0">{{ illustrate.statementPayment[1].value }}</span>
                  <span class="lx-flex-shrink-0">{{ t('DockOrderOnlineQuotation.default.s3-2') }}</span>
                  <span class="lx-flex-shrink-0">{{ illustrate.statementPayment[2].value }}</span>
                  <span class="lx-flex-shrink-0">{{ t('DockOrderOnlineQuotation.default.s3-3') }}</span>
                </div>
              </div>
            </div>
            <div class="item mt-2">
              <div class="label">{{ t('DockOrderOnlineQuotation.sm_l4') }}:</div>
              <div class="value">
                <div class="lx-flex-start">
                  <span class="lx-flex-shrink-0">{{ t('DockOrderOnlineQuotation.default.s4-1') }}</span>
                  <span class="lx-flex-shrink-0">{{ illustrate.statementDelayPenalty[0].value }}</span>
                  <span class="lx-flex-shrink-0">{{ t('DockOrderOnlineQuotation.default.s4-2') }}</span>
                  <span class="lx-flex-shrink-0">{{ illustrate.statementDelayPenalty[1].value }}</span>
                  <span class="lx-flex-shrink-0">{{ t('DockOrderOnlineQuotation.default.s4-3') }}</span>
                </div>
              </div>
            </div>
            <div class="item mt-2">
              <div class="label">{{ t('DockOrderOnlineQuotation.sm_l5') }}:</div>
              <div class="value">
                <div class="lx-flex-start">
                  <span class="lx-flex-shrink-0">{{ t('DockOrderOnlineQuotation.default.s5-1') }}</span>
                  <span class="lx-flex-shrink-0">{{ illustrate.statementValidity[0].value }}</span>
                  <span class="lx-flex-shrink-0">{{ t('DockOrderOnlineQuotation.default.s5-2') }}</span>
                </div>
              </div>
            </div>
<!--            <div
              class="item mt-2"
              v-if="info.dockShowInfoVo.quoteOrderCurrency === 'currency_1'"
            >
              <div class="label">{{ t('DockOrderOnlineQuotation.t17') }}:</div>
              <div class="value">{{ formData.rate }}%</div>
            </div>-->
            <div class="item mt-2">
              <div class="label">{{ t('DockOrderOnlineQuotation.t48') }}:</div>
              <div class="value" style="white-space: pre-wrap">
                {{ formData.quoteDescription }}
              </div>
            </div>
          </div>
        </div>

        <div class="info grid-2 mt-3">
          <div class="flexsc">
            {{ t('dockRepair.label3') }}：<b>{{ getDictLabel('currency', info.dockShowInfoVo.quoteOrderCurrency) }}</b>
          </div>
          <div class="flexec" style="padding-right: 200px">
            {{ t('dockRepair.label4') }}：<b>{{ getDictLabel('currency', info.dockShowInfoVo.payCurrency) }}</b>
          </div>
        </div>

        <div class="info mt-3" v-if="info.dockQuotationAggregate">
          <div class="tit">{{ t('DockOrderOnlineQuotation.t19') }}</div>
          <div class="con">
            <el-table :data="info.dockQuotationAggregate" style="width: 100%" :header-row-style="{ backgroundColor: '#F0F3F8' }" :row-class-name="tableRowClassName">
              <el-table-column :label="t('DockOrderOnlineQuotation.t19_1')" align="center" prop="projectName"> </el-table-column>
              <el-table-column :label="t('DockOrderOnlineQuotation.t20')" align="center" prop="feeSummary">
                <template #default="scope">
                  <template v-if="scope.row.key === 'offer'">
                    <template v-if="type === 'add'">
                      <el-input-number :controls="false" v-model="formData[scope.row.key]" :min="0" :max="100" ></el-input-number>
                      %
                    </template>
                    <template v-else> {{ scope.row.feeSummary }}% </template>
                  </template>
                  <template v-else-if="scope.row.key === 'amountAfterOffer'">
                    {{ amountFormat(formData[scope.row.key]) }}
                  </template>
                  <template v-else>
                    {{ amountFormat(scope.row.feeSummary) }}
                  </template>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-form>

      <!-- <div class="info mt-3">
        <div class="tit">{{ t('DockOrderOnlineQuotation.t29') }}</div>
        <div class="con flexsb mt-2">
          <div>{{ t('DockOrderOnlineQuotation.t30') }}: {{ info.dockShowInfoVo.createByName }}</div>
          <div>{{ t('DockOrderOnlineQuotation.t31') }}: {{ dateFormat(info.dockShowInfoVo.createTime) }}</div>
          <div>{{ t('DockOrderOnlineQuotation.t32') }}: {{ dateFormat(info.dockShowInfoVo.updateTime) }}</div>
          <div>{{ t('DockOrderOnlineQuotation.t33') }}: {{ dateFormat(info.dockShowInfoVo.quotationEndTime) }}</div>
        </div>
      </div> -->

      <div class="info mt-3">
        <div class="tit">
          {{ t('DockOrderOnlineQuotation.t34') }}
        </div>
        <div class="con mt-2">
          {{ info.dockShowInfoVo.remark }}
        </div>
      </div>

      <div class="info mt-3">
        <!-- <el-icon
          v-if="locale === 'zh-CN' && type === 'add'"
          class="icon"
          @click="tipDialog = true"
        >
          <QuestionFilled />
        </el-icon> -->
        <div :class="['table', 'mt-2', locale]" @mouseover.once="onMouseover">
          <el-auto-resizer>
            <template #default="{ height, width }">
              <el-table-v2 :columns="columns" :data="tableData" :width="width" :height="height" :row-class="setRowClass" fixed>
                <template #row="props">
                  <Row v-bind="props" />
                </template>
              </el-table-v2>
            </template>
          </el-auto-resizer>
        </div>
      </div>

      <div class="info mt-3">
        <div class="tit">
          {{ t('attachments') }}
        </div>
        <div class="con mt-2" v-if="type === 'add'">
          <Uploads ref="UploadsRef" @change="fileChange" :tip="t('Uploads.t2')" />
        </div>

        <div
          class="con mt-2"
          v-if="type === 'detail'"
        >
          <div
            v-for="(item, index) in info.urlList"
            :key="index"
          >
            <a
              :href="item.url"
              target="_blank"
            >
              {{ item.file_name }}
            </a>
          </div>
        </div>
      </div>

      <div class="buttons flexcc mt-4">
        <!-- <div class="flexsc">{{ t('DockOrderOnlineQuotation.t27') }}: {{ info.dockShowInfoVo.orderNo }}</div>
          <div class="flexsc">{{ t('DockOrderOnlineQuotation.t28') }}: {{ info.dockShowInfoVo.dockOrderName }}</div> -->
        <div class="flexec" v-if="type === 'add'">
          <el-button type="primary" color="#252628" @click="handleSave">
            {{ t('save') }}
          </el-button>
          <el-button v-if="isAdmin" type="primary" @click="hanldleSubmit">
            {{ t('DockOrderOnlineQuotation.t6') }}
          </el-button>
        </div>

        <div class="flexec" v-if="type === 'detail'">
          <el-button @click="handleExport" color="#252628">
            {{ t('export') }}
          </el-button>
          <el-button @click="handelSendMsg" type="primary">
            {{ t('DockOrderOnlineQuotation.t7') }}
          </el-button>
          <el-button v-if="info.status === '4' && info.canConfirmQuota" color="#252628" @click="handleConfirmBid">
            {{ t('DockOrderOnlineQuotation.t8') }}
          </el-button>
        </div>
      </div>
    </div>

    <!-- 设置访问密码 -->
    <AccessPassword v-if="dialogAccessPassword" :visible="dialogAccessPassword" @close="dialogAccessPassword = false" @setAccessPassword="setAccessPassword" />

    <!-- 确认中标 -->
    <ConfirmBid v-if="dialogConfirmBid" :visible="dialogConfirmBid" :objId="editId" type="dockRepair" @close="dialogConfirmBid = false" @getList="getDetail" />

    <!-- 提交确认 -->
    <Confirm v-if="submitConfirmDialog" :visible="submitConfirmDialog" :text="t('DockOrderOnlineQuotation.c1')" @close="submitConfirmDialog = false" @cancel="submitConfirmDialog = false" @confirm="submitConfirmFn" />

    <!-- 提示 -->
    <Confirm v-if="tipDialog" :visible="tipDialog" title="友情提示" hideCancelbtn @close="tipDialog = false" @cancel="tipDialog = false" @confirm="tipDialog = false">
      <div class="tip">
        <h2>如您在中文网页下做报价，请注意：</h2>
        <p class="mt-2">1、<b>船东声明和特别要求</b>：客户在英文网页环境下输入的内容可能与中文不完全一致，建议您参考英文网页的原文内容；</p>
        <p>2、修理项目中凡是客户编辑过的内容，将会以英文展示在中文网页；</p>
        <p>3、非报价性的解答性答复，请填入“备注”栏。</p>
      </div>
    </Confirm>
  </div>
</template>

<script setup lang="jsx">
import { ref, reactive, onBeforeMount, watch, unref, computed, nextTick, cloneVNode } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { viewBeforeApi, queryQuotationByIdApi, viewOuotationApi, quotoImportancePriceListApi, saveQuotationApi, submitQuotationApi, updateQuotoDetailApi, exportDockQuoteApi } from '@/service/dockOrder'
import { dateFormat, setItemNumber, download, amountFormat } from '@/utils/index'
import { uploads } from '@/service/common'
import Decimal from 'decimal.js'
import moment from 'moment'
import useLogin from '@/stores/login'
import useDialogue from '@/stores/dialogue'
import { debounce } from 'lodash'

import AccessPassword from '@/views/userCenter/AccessPassword.vue'
import Uploads from '@/components/Uploads.vue'
import ConfirmBid from '../shipowner/ConfirmBid.vue'
import Confirm from '@/components/Confirm.vue'

import useDict from '@/hooks/useDict'
const { dictData, getDictData, getDictLabel } = useDict()

onBeforeMount(() => {
  init()
})

const { t, locale } = useI18n()
watch(locale, () => {
  init()
})

const router = useRouter()
const route = useRoute()
const storeLogin = useLogin()

const storeDialogue = useDialogue()
const { setDialogVisible, setActivePerson } = storeDialogue

const id = route.query.id
const type = computed(() => {
  let res = 'detail'

  // 维修服务商 && 报价员
  if (storeLogin.userInfo.registerClassCode === 'wxfws' && storeLogin?.userInfo?.id == route.query.quotaCreateBy) {
    res = 'add'
  }


  return res
})
const isShipownerView = ref(storeLogin.userInfo.registerClassCode === 'wxxqf') // 船东查看报价

// 是否是管理员
const isAdmin = computed(() => {
  return storeLogin?.userInfo?.isAdmin === '1'
})
// 是否是船东/船管
const isChd = computed(() => {
  return storeLogin?.userInfo?.customerClassCode === '05' || storeLogin?.userInfo?.customerClassCode === '06'
})

const onMouseover = () => {
  locale.value === 'zh-CN' && !isChd.value ? tipDialog.value = true : ''
}

// 导出
const handleExport = () => {
  exportDockQuoteApi({ quotationId: id }).then((res) => {
    download(res)
  })
}

// 报价说明
const illustrate = ref({
  statementRepairPeriod: [
    {
      value: 1
    },
    {
      value: 1
    },
    {
      value: 1
    }
  ],
  statementPayment: [
    {
      value: 1
    },
    {
      value: 1
    },
    {
      value: 1
    }
  ],
  statementDelayPenalty: [
    {
      value: 1
    },
    {
      value: 1
    }
  ],
  statementValidity: [
    {
      value: 1
    }
  ]
})
watch(illustrate.value, (val) => {
  Object.entries(val).forEach((item) => {
    formData.value[item[0]] = item[1].map((citem) => citem.value).join()
  })
})

// 保存报价单
const saveSubmit = async () => {
  const params = {
    id,
    ...formData.value
  }

  params.urlList = await handleUpload()

  saveQuotationApi(params).then(({ msg }) => {
    ElMessage.success(msg)
    getDetail()
  })
}
const handleSave = () => {
  if (!formData.value.quotationNo) {
    ElMessage.warning(t('DockOrderOnlineQuotation.t39'))
    return
  }

  const data = unref(tableData.value)
  if (data.some((item) => !item.isSave)) {
    ElMessage.warning(t('DockOrderOnlineQuotation.w1'))
    return
  }

  if (!formEl.value) return
  formEl.value.validate((valid, fields) => {
    if (valid) {
      // 如果未设置密码
      if (!info.value.accessPassword) {
        dialogAccessPassword.value = true
        return
      }
      saveSubmit()
    }
  })
}

// 提交报价单
const submitConfirmDialog = ref(false)
const hanldleSubmit = () => {
  if (!formData.value.quotationNo) {
    ElMessage.warning(t('DockOrderOnlineQuotation.t39'))
    return
  }

  const data = unref(tableData.value)
  if (data.some((item) => !item.isSave)) {
    ElMessage.warning(t('DockOrderOnlineQuotation.w1'))
    return
  }

  if (!formEl.value) return
  formEl.value.validate((valid, fields) => {
    if (valid) {
      // 如果未设置密码
      if (!info.value.accessPassword) {
        dialogAccessPassword.value = true
        return
      }
      submitConfirmDialog.value = true
    }
  })
}
const submitConfirmFn = async () => {
  const params = {
    id,
    ...formData.value
  }
  params.urlList = await handleUpload()
  submitQuotationApi(params).then(({ msg }) => {
    ElMessage.success(msg)
    submitConfirmDialog.value = false
    router.go(-1)
  })
}

// 发消息
const handelSendMsg = () => {
  const activePerson = {
    // 船东船管给修船厂发
    wxxqf: {
      customerName: info.value.quotaCreateByName,
      customerId: info.value.quotaCreateBy
    },
    // 修船厂给创建人(船东船管)发
    wxfws: {
      customerName: info.value.dockShowInfoVo.createByName,
      customerId: info.value.dockShowInfoVo.createBy
    }
  }
  setDialogVisible(true)
  setActivePerson(activePerson[storeLogin.userInfo.registerClassCode])
}

// 正在操作的id
const editId = ref(null)

// 确认中标
const dialogConfirmBid = ref(false)
const handleConfirmBid = (item) => {
  dialogConfirmBid.value = true
  editId.value = id
}

// 表单
const formEl = ref(null)
const formData = ref({
  quotationImportList: []
})
const validator = {
  item1: (rule, value, callback) => {
    if (!formData.value.statementRepairPeriodOne || !formData.value.statementRepairPeriodTwo || !formData.value.statementRepairPeriodThree) {
      return callback(new Error(t('DockOrderOnlineQuotation.m1')))
    }
    callback()
  },
  item3: (rule, value, callback) => {
    if (!formData.value.statementPaymentOne || !formData.value.statementPaymentTwo || !formData.value.statementPaymentThree) {
      return callback(new Error(t('DockOrderOnlineQuotation.m1')))
    }
    callback()
  },
  item4: (rule, value, callback) => {
    if (!formData.value.statementDelayOne || !formData.value.statementDelayTwo) {
      return callback(new Error(t('DockOrderOnlineQuotation.m1')))
    }
    callback()
  }
}
const rules = computed(() => {
  return {
    // item1: [{ required: true, validator: validator.item1, trigger: 'change' }],
    // item3: [{ required: true, validator: validator.item3, trigger: 'change' }],
    // item4: [{ required: true, validator: validator.item4, trigger: 'change' }],
    // statementValidityOne: [{ required: true, message: t('DockOrderOnlineQuotation.m1'), trigger: 'change' }],
    // rate: [{ required: true, message: t('DockOrderOnlineQuotation.t45'), trigger: 'change' }]
  }
})

// 访问密码 弹窗
const dialogAccessPassword = ref(false)
// 设置访问密码
const setAccessPassword = (val) => {
  formData.value.accessPassword = val
  saveSubmit()
}

// 查询报价重要单价列表
const optionsImportancePrice = ref([])
const getQuotoImportancePrice = () => {
  quotoImportancePriceListApi().then(({ data }) => {
    optionsImportancePrice.value = data
  })
}
const importanceTypeChange = (val, row) => {
  row.dockQuotationId = Number(id)
  const item = optionsImportancePrice.value.find((item) => item.id === val)
  if (item) {
    row.unit = item.unit
    row.importanceType = item.importanceType
  }
}
const optionsImportancePriceDisabled = (item) => {
  return formData.value.quotationImportList.some((p) => p.projectId && item.id === p.projectId)
}

// 验证密码
const checkPasswordFormEl = ref(null)
const checkPasswordFormData = ref({})
const checkPasswordRules = {
  accessPassword: [{ required: true, message: t('DockOrderOnlineQuotation.t47'), trigger: 'change' }]
}
const isExpired = ref(false) // 超过报价单截止日期
// 是否需要密码验证
const isCheckPassword = computed(() => {
  // 如果逾期 或 无密码 或 已开标
  if (isExpired.value || !info.value.accessPassword || info.value.status === '2') {
    isValidPassword.value = true
    return false
  }
  // 有密码 && 密码未通过
  return info.value.accessPassword && !isValidPassword.value
})
const isValidPassword = ref(false) // 密码是否验证通过
const handleCheckPassword = () => {
  if (!checkPasswordFormEl.value) return
  checkPasswordFormEl.value.validate((valid, fields) => {
    if (valid) {
      viewBeforeApi({
        id,
        ...checkPasswordFormData.value
      }).then(() => {
        isValidPassword.value = true
        getDetail()
      })
    }
  })
}

const tipDialog = ref(false)

// 优惠行
const setOfferRow = (dockQuotationAggregate, offer, amountAfterOffer) => {
  dockQuotationAggregate[dockQuotationAggregate.length - 1].key = 'totalPrice' // 原总价
  info.value.dockQuotationAggregate = [
    ...dockQuotationAggregate,
    {
      projectName: t('DockOrderOnlineQuotation.projectName1'),
      feeSummary: offer || 0,
      key: 'offer'
    },
    {
      projectName: t('DockOrderOnlineQuotation.projectName2'),
      feeSummary: amountAfterOffer || null,
      key: 'amountAfterOffer'
    }
  ]
}

// 报价单详情
const info = ref(null)
const getDetail = async () => {
  let apiFun = queryQuotationByIdApi

  if (isShipownerView.value) {
    apiFun = viewOuotationApi
  }

  await apiFun({ quotationId: id }).then(({ data }) => {
    data.dockShowInfoVo.remark = data.dockShowInfoVo.remark === '以下维修项目以报价为目的，仅供报价参考使用，实际修理技术要求和工艺要求及验收标准，以船东、船级社、船厂质量标准为主；' || data.dockShowInfoVo.remark === "The main purpose of this list is for yard's quotation, all technical requirements of repair items to be complied with Owner, Class and Yard's quality standards / practice." ? t('dockRepair.statementValue') : data.dockShowInfoVo.remark
    info.value = data
    const { dockShowInfoVo, quotationNo, totalRepairPeriod, repairInDock, quotationStandards, payDescription, quotationValidityTime, rate, delayPenalty, quoteDescription, quotationImportList, dockQuotationDetailList, urlList, dockQuotationAggregate, offer, amountAfterOffer, statementRepairPeriod, statementPrice, statementPayment, statementDelayPenalty, statementValidity } = data

    setOfferRow(dockQuotationAggregate, offer, amountAfterOffer)
    isExpired.value = Number(moment().format('X')) > Number(dockShowInfoVo.quotationEndTime) // 今天大于截止日期 为逾期

    // 表单回显
    formData.value = {
      quotationNo: formData.value.quotationNo || quotationNo,
      // totalRepairPeriod,
      // repairInDock,
      // quotationStandards,
      // payDescription,
      // quotationValidityTime,
      rate,
      // delayPenalty,
      quoteDescription: quoteDescription || t('DockOrderOnlineQuotation.default.s6'),
      quotationImportList: quotationImportList || [],
      offer: formData.value.offer || offer,
      amountAfterOffer
    }
    Object.keys(illustrate.value).forEach((key) => {
      if (!data[key]) return
      illustrate.value[key] = data[key]?.split(',').map((citem) => {
        return { value: citem }
      })
    })

    if (urlList) {
      fileList.value = urlList.map((item) => {
        return {
          name: item.file_name,
          url: item.url
        }
      })
    }

    if (type.value === 'add') {
      nextTick(() => {
        if (UploadsRef.value) {
          UploadsRef.value.setFileList(fileList.value)
        }
      })
    }

    // 坞修单明细
    if (dockQuotationDetailList) {
      dockQuotationDetailList.forEach((item) => {
        item.isSave = true
        item.amount = item.amount || null
      })
      tableData.value = dockQuotationDetailList
      setItemNumber(dockQuotationDetailList)
    }
  })
}

// 监听 折扣、优惠
watch(
  [() => formData.value.rate, () => formData.value.offer, info],
  ([rate, offer, info]) => {
    if (!info) return
    const oldTotalPrice = info.dockQuotationAggregate.find((item) => item.key === 'totalPrice')?.feeSummary
    // console.log(oldTotalPrice);

    // （总价：原总价×(1-总折扣%)）
    const totalPrice = new Decimal(oldTotalPrice).mul(1 - (rate || 0) / 100).toNumber()
    // 优惠后总价=总价x(1-优惠%）
    formData.value.amountAfterOffer = new Decimal(totalPrice).mul(1 - (offer || 0) / 100).toFixed(2, Decimal.ROUND_DOWN)
  },
  { deep: true }
)

//
const tableRowClassName = ({ row, rowIndex }) => {
  if (['totalPrice', 'offer', 'amountAfterOffer'].includes(row.key)) {
    return 'pink'
  }
  return ''
}

// 表格 列
const columns = ref([])
const tableData = ref([])

// 行 class
const setRowClass = ({ columns, rowData, rowIndex }) => {
  // console.log(columns, rowData, rowIndex, '---')
  let str = ''

  if (rowData.projectLevel !== null) {
    str += ` projectLevel-${rowData.projectLevel}`
  }

  if (!rowData.isSave) {
    str += ' no-save'
  }

  return str
}

const Row = ({ rowData, rowIndex, cells, columns }) => {
  // console.log(rowData, rowIndex, cells, columns)

  const style = {
    backgroundColor: '#F8CD95'
  }

  const fn = (key) => {
    const index = columns.findIndex((item) => item.dataKey === key)
    if (index !== -1) {
      cells[index] = rowData[key] ? cloneVNode(cells[index], { style }) : cloneVNode(cells[index])
    }
  }

  if (rowData.modifyOrNotPrice === 1) {
    fn('price')
  }
  if (rowData.modifyOrNotDiscount === 1) {
    fn('discount')
  }
  if (rowData.modifyOrNotAmount === 1) {
    fn('amount')
  }
  if (rowData.modifyOrNotRemark === 1) {
    fn('remark')
  }

  return cells
}

const getColumns = () => {
  const setRef = (el) => {
    if (el) {
      el.focus?.()
    }
  }

  const editingClassName = { 'table-v2-inline-editing-trigger': type.value === 'add' }

  // 保存
  const handleRowSave = debounce(
    (rowData) => {
      const { id, price, discount, amount, remark } = rowData
      updateQuotoDetailApi({ id, price, discount, amount, remark }).then(({ msg, data }) => {
        ElMessage.success(msg)
        rowData.isSave = true
        rowData.editingKey = null
        setOfferRow(data, formData.value.offer)
      })
    },
    500,
    {
      leading: true, // 延长开始后调用
      trailing: false // 延长结束前调用
    }
  )

  // 回车保存
  const handleEnterSave = (e, rowData) => {
    if (['Enter', 'NumpadEnter'].includes(e.code)) {
      handleRowSave(rowData)
    }
  }

  // 计算折扣
  const compute = (rowData) => {
    const { requireCount, price, discount } = rowData
    // activeItem.amount = requireCount * price * (1 - discount * 0.01)
    rowData.amount = Number(
      Decimal(requireCount || 0)
        .mul(Decimal(price || 0))
        .mul(Decimal(1).sub(Decimal(discount || 0).mul(0.01)))
    )
  }

  const hiddenDis = info.value.dockShowInfoVo.quoteOrderCurrency === 'currency_0' // 币种为'人民币'时隐藏

  columns.value = [
    {
      title: t('dockRepair.coltit1'), // 项目编号
      key: 'itemNumber',
      dataKey: 'itemNumber',
      width: 100,
      class: 'itemNumber',
      align: 'center'
    },
    {
      title: t('dockRepair.coltit2'), // 项目类型
      key: 'projectName',
      dataKey: 'projectName',
      width: hiddenDis ? 500 : 420,
      cellRenderer: ({ rowData, rowIndex }) => {
        return `${rowData.projectName} ${rowData.projectContent || ''}`
      }
    },
    // {
    //   title: t('dockRepair.coltit3'), // 项目类型说明
    //   key: 'projectContent',
    //   dataKey: 'projectContent',
    //   width: 150,
    //   cellRenderer: ({ rowData, rowIndex }) => {
    //     return rowData.projectContent
    //   }
    // },
    {
      title: t('dockRepair.coltit4'), // 单位
      key: 'unit',
      dataKey: 'unit',
      width: 110,
      align: 'center'
    },
    {
      title: t('dockRepair.coltit5'), // 数量
      key: 'requireCount',
      dataKey: 'requireCount',
      width: 110,
      align: 'center',
      cellRenderer: ({ rowData, rowIndex }) => {
        return amountFormat(rowData.requireCount)
      }
    },
    {
      title: t('userCenter.price'), //
      key: 'price',
      dataKey: 'price',
      width: 110,
      align: 'center',
      cellRenderer: ({ rowData, rowIndex }) => {
        if ([0, 1].includes(rowData.projectLevel)) return

        watch(
          () => rowData.price,
          (newVal) => {
            // if (!newVal) return
            compute(rowData)
          }
        )

        if (rowData.editingKey === 'price') {
          return (
            <el-input-number
              ref={setRef}
              v-model={rowData.price}
              controls={false}
              min={0}
              onBlur={() => {
                handleRowSave(rowData)
              }}
              onKeyup={(e) => handleEnterSave(e, rowData)}
            />
          )
        }

        const onEnterEditMode = () => {
          if (type.value === 'add') {
            rowData.editingKey = 'price'
          }
        }

        return (
          <div class={editingClassName} onClick={onEnterEditMode}>
            {amountFormat(rowData.price)}
          </div>
        )
      }
    },
    {
      title: t('userCenter.discount'), //
      key: 'discount',
      dataKey: 'discount',
      width: 110,
      align: 'center',
      hidden: hiddenDis,
      cellRenderer: ({ rowData, rowIndex }) => {
        if ([0, 1].includes(rowData.projectLevel)) return

        watch(
          () => rowData.discount,
          (newVal) => {
            compute(rowData)
          }
        )

        if (rowData.editingKey === 'discount') {
          return (
            <el-input-number
              ref={setRef}
              v-model={rowData.discount}
              controls={false}
              min={0}
              onBlur={() => {
                handleRowSave(rowData)
              }}
              onKeyup={(e) => handleEnterSave(e, rowData)}
            />
          )
        }

        const onEnterEditMode = () => {
          if (type.value === 'add') {
            rowData.editingKey = 'discount'
          }
        }

        return (
          <div class={editingClassName} onClick={onEnterEditMode}>
            {rowData.discount !== null ? `${rowData.discount}%` : ''}
          </div>
        )
      }
    },
    {
      title: t('userCenter.amount'), //
      key: 'amount',
      dataKey: 'amount',
      width: 110,
      align: 'center',
      cellRenderer: ({ rowData, rowIndex }) => {
        rowData.amount = rowData.amount || null
        if ([0, 1].includes(rowData.projectLevel)) return
        if (rowData.editingKey === 'amount') {
          // return (
          //   <el-input-number
          //     ref={setRef}
          //     v-model={rowData.amount}
          //     controls={false}
          //     min={0}
          //     onBlur={() => {
          //       handleRowSave(rowData)
          //     }}
          //     onKeyup={(e) => handleEnterSave(e, rowData)}
          //   />
          // )
          return <div>{rowData.amount}</div>
        }

        const onEnterEditMode = () => {
          if (type.value === 'add') {
            rowData.editingKey = 'amount'
          }
        }

        return (
          <div class={editingClassName} onClick={onEnterEditMode}>
            {amountFormat(rowData.amount)}
          </div>
        )
      }
    },
    {
      title: t('userCenter.remark'), //
      key: 'remark',
      dataKey: 'remark',
      width: hiddenDis ? 170 : 140,
      align: 'center',
      cellRenderer: ({ rowData, rowIndex }) => {
        if ([0, 1].includes(rowData.projectLevel)) return

        if (rowData.editingKey === 'remark') {
          return (
            <el-input
              ref={setRef}
              v-model={rowData.remark}
              onBlur={() => {
                handleRowSave(rowData)
              }}
              onKeyup={(e) => handleEnterSave(e, rowData)}
            />
          )
        }

        const onEnterEditMode = () => {
          if (type.value === 'add') {
            rowData.editingKey = 'remark'
          }
        }
        return (
          <div class={editingClassName} onClick={onEnterEditMode}>
            {rowData.remark}
          </div>
        )
      }
    }
  ]

  if (type.value === 'add') {
    return
    columns.value.push({
      title: t('dockRepair.coltit6'), // 操作
      width: 100,
      fixed: 'right',
      cellRenderer: ({ rowData, rowIndex }) => {
        if ([0, 1].includes(rowData.projectLevel)) {
          return
        }

        // 保存
        const handleRowSave = () => {
          const { id, price, discount, amount, remark } = rowData
          updateQuotoDetailApi({ id, price, discount, amount, remark }).then(({ data, msg }) => {
            info.value.dockQuotationAggregate = data
            ElMessage.success(msg)
            rowData.isSave = true
          })
        }

        // 编辑
        const handleRowEdit = (value) => {
          rowData.isSave = false
        }

        return <>{rowData.isSave ? <img src={new URL('@/assets/img/icon_bianji.png', import.meta.url)} height="22" class="mr-2" onClick={handleRowEdit} /> : <img src={new URL('@/assets/img/icon_baocun.png', import.meta.url)} height="22" class="mr-2" onClick={handleRowSave} />}</>
      }
    })
  }
}

// 文件列表
const fileList = ref([])
const fileChange = (val) => {
  fileList.value = val
}
const UploadsRef = ref(null)
const handleUpload = () => {
  return new Promise((resolve, reject) => {
    const newList = fileList.value.filter((item) => item.raw)
    const oldList = fileList.value.filter((item) => !item.raw).map((item) => {
      return {
        url: item.url,
        name:  item.name
      }
    })

    if (newList.length) {
      const formData = new FormData()
      newList.forEach((item) => {
        formData.append('files', item.raw)
      })
      uploads(formData).then(({ urls, fileNames }) => {
        const newUrls = urls.split(',')
        fileList.value = newUrls.map((newUrl, newUrlIndex) => {
          return {
            name: fileNames.split(',')[newUrlIndex],
            url: newUrl
          }
        })
        UploadsRef.value.setFileList(fileList.value)
        resolve([...oldList, ...newUrls.map((url, index)=>{
          return {
            url,
            name: fileNames.split(',')[index]
          }
        })])
      })
    } else {
      resolve(oldList)
    }
  })
}

//
const init = async () => {
  getDictData('currency')
  getQuotoImportancePrice()
  getDictData('ships_type')
  getDictData('classification_society')
  await getDetail()
  getColumns()
}
</script>

<style scoped lang="scss">
.DockOrderOnlineQuotation {
  background: #f5f5f5;
  padding: 30px 0;
  margin-bottom: -76px;

  .keyword .con {
    gap: 20px;
    .item {
      cursor: default;
      color: #252628;
      background: #f0f3f8;
      padding: 15px 40px;
      border-radius: 4px;
    }

    .item:last-child {
      margin-right: auto;
    }
  }

  .el-button {
    min-width: 140px;
  }

  .addbtn {
    color: var(--mainColor);
    cursor: pointer;
  }

  .checkPassword {
    padding: 100px 400px;
  }

  .buttons {
    :deep(.el-button) {
      height: 45px;
      min-width: 200px;
    }
  }

  :deep(.pink) {
    background: #fff3f0;
    color: #252628;
    font-weight: bold;
  }

  .grid-3 {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 30px;
  }

  .info {
    background: #fff;
    padding: 24px;

    > .tit {
      border-bottom: 2px solid #252628;
      font-weight: bold;
      padding: 10px 0;
      text-transform: uppercase;
    }

    &.sm {
      .con {
        .item {
          display: grid;
          grid-template-columns: 100px auto;
          gap: 10px;
        }
      }

      :deep(.el-input-number .el-input__inner) {
        text-align: left;
      }
    }

    .icon {
      transform: scale(1.3);
      cursor: pointer;
    }
  }

  :deep(.el-table th.el-table__cell) {
    background: none !important;
    color: #252628;
  }

  .ship {
    display: grid;
    // grid-template-columns: 272px auto;
    // gap: 30px;

    .left {
      width: 100%;
      height: 180px;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }

    .right {
      .title {
        .a {
          font-size: 20px;
          font-weight: bold;
        }

        .b {
          min-width: 180px;
          padding: 0 10px;
          height: 38px;
          background: rgba($color: #3376e5, $alpha: 0.1);
          color: #3376e5;
          border-radius: 4px;
        }
      }

      .attr {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        row-gap: 15px;

        span {
          font-size: 12px;

          &:first-of-type {
            color: #9d9fa5;
            margin-right: 5px;
          }
        }
      }
    }
  }

  .table {
    border-top: 2px solid #252628;
    height: 700px;

    :deep(.table-v2-inline-editing-trigger) {
      border: 1px transparent dotted;
      padding: 4px;
      min-height: 26px;
      min-width: 100%;
      cursor: text;
      border-radius: 3px;
    }

    :deep(.table-v2-inline-editing-trigger:hover) {
      border-color: var(--el-color-primary);
    }

    :deep(.el-table-v2__header-cell) {
      background: #f0f3f8;
      color: #252628;
    }

    :deep(.no-save) {
      background: #f9ecd9;
    }

    :deep(.projectLevel-0) {
      background: #f7f9fb;
    }

    :deep(.projectLevel-0),
    :deep(.projectLevel-1),
    :deep(.projectLevel-2) {
      .itemNumber {
        justify-content: center;
      }
    }

    :deep(.projectLevel-3),
    :deep(.projectLevel-4) {
      .itemNumber {
        justify-content: right;
      }
    }

    // &.en {
    :deep(.el-table-v2__header-cell) {
      font-family: 'Sitka Display Semibold';
      justify-content: center;
      * {
        font-size: 17px;
      }
    }

    :deep(.projectLevel-0) {
      font-family: 'Amasis MT Pro Medium';

      * {
        font-size: 17px;
        font-weight: bold;
      }
    }

    :deep(.projectLevel-1) {
      font-family: '等线';

      * {
        font-size: 16px;
        font-weight: bold;
      }
    }

    :deep(.projectLevel-2, .projectLevel-3, .projectLevel-4) {
      font-family: 'Abadi';

      * {
        font-size: 15px;
      }
    }
    // }
  }

  :deep(.el-date-editor.el-input) {
    width: 100%;

    .el-input__wrapper {
      width: 100%;
    }
  }

  .tip {
    color: #252628;
  }
}
.illustrate-input {
  width: 64px;
  :deep(.el-input__inner[type='number']) {
    text-align: center;
  }
}
:deep(.el-input__inner::-webkit-outer-spin-button),
:deep(.el-input__inner::-webkit-inner-spin-button) {
  -webkit-appearance: none !important;
  margin: 0;
}
:deep(.el-input__inner[type='number']) {
  -moz-appearance: textfield;
}
</style>
